package com.bite.friend.service.question.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.common.security.exception.ServiceException;
import com.bite.friend.domain.question.Question;
import com.bite.friend.domain.question.dto.QuestionQueryDTO;
import com.bite.friend.domain.question.es.QuestionES;
import com.bite.friend.domain.question.vo.QuestionVO;
import com.bite.friend.domain.question.vo.QuestionDetailVO;
import com.bite.friend.domain.user.UserSubmit;
import com.bite.friend.elasticsearch.QuestionRepository;
import com.bite.friend.manager.QuestionCacheManager;
import com.bite.friend.manager.UserSubmitCacheManager;
import com.bite.friend.mapper.question.QuestionMapper;
import com.bite.friend.service.question.IQuestionService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionService implements IQuestionService {

    @Value("${question.hot.queryCount:5}")
    private Integer hotQueryCount;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private UserSubmitCacheManager userSubmitCacheManager;



    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestionES();
        }
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyContent = questionQueryDTO.getKeyword();
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);

        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyContent)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyContent)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyContent, keyContent, pageable);
        } else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyContent, keyContent, difficulty, pageable);
        }

        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();

        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);

        return TableDataInfo.success(questionVOList, total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId, Long examId) {
        if (questionId == null) {
            throw new ServiceException(ResultCode.QUESTION_NOT_EXIST);
        }
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES == null) {
            refreshQuestionES();
            questionES = questionRepository.findById(questionId).orElse(null);
        }
        if (questionES == null) {
            // 说明数据库中没有但是Redis中有
            questionCacheManager.delIdFromQuestionList(questionId);
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        BeanUtil.copyProperties(questionES, questionDetailVO);
        updateSubmitMainCode(questionId, examId, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long size = questionCacheManager.getListAllSize();
        if (size == null || size <= 0) {
            questionCacheManager.refreshAllCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long size = questionCacheManager.getListAllSize();
        if (size == null || size <= 0) {
            questionCacheManager.refreshAllCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    @Override
    public List<QuestionVO> hotList() {
        PageHelper.startPage(0, hotQueryCount);
        Long size = questionCacheManager.getHotListSize();
        if (size == null || size <= 0) {
            questionCacheManager.refreshHotListCache();
            size = questionCacheManager.getHotListSize();
        }
        if (size == null || size < 0) {
            return List.of();
        }
        List<QuestionVO> hostList = questionCacheManager.getHostList();
        return hostList;
    }

    private void refreshQuestionES() {
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<>());
        if (CollectionUtil.isEmpty(questions)) {
            return;
        }
        List<QuestionES> questionES = BeanUtil.copyToList(questions, QuestionES.class);
        questionRepository.saveAll(questionES);
    }


    // 如果用户有代码 就更新默认的代码块
    private void updateSubmitMainCode(Long questionId, Long examId, QuestionDetailVO questionDetailVO) {
        // 查看这个用户是否已经打过题目 如果有那么就将原先的题目赋值给ta
        String submitMainCode = userSubmitCacheManager.getSubmitMainCode(ThreadLocalUtil.getUserId(), questionId, examId, null);
        if (StrUtil.isNotEmpty(submitMainCode)) {
            questionDetailVO.setDefaultCode(submitMainCode);
        }
    }
}
